import React, { useEffect, useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import shortid from "shortid"
import decode from 'jwt-decode'
const LoginForm = props => {
    const mapProps = useSelector(state => state)
    const state = useSelector(state => state.login)
    const params = {
        username: '',
        password: ''
    }
    const [formData, setFormData] = useState(params)
    const changeInfo = e => {
        setFormData({
            ...formData,
            [e.target.name]: e.target.value
        })
    }
    const submit = async e => {
        e.preventDefault();
        if(localStorage.getItem("@TOKEN")) {
            return props.flashFn.addFlashAc({
                type: 'alert-danger',
                text: '已登录',
                id: shortid.generate(),
                closeTime: 1000
            })
        }
        console.log(props, mapProps);
        const { data } = await props.loginFn.loginAc(formData)
        if (data.status !== 0) {
            return props.flashFn.addFlashAc({
                type: 'alert-danger',
                text: '登录失败',
                id: shortid.generate(),
                closeTime: 1000
            })
        }
        const token = data.token

        localStorage.setItem("@TOKEN", token)

        props.loginFn.syncInfoAc(decode(token))
        props.history.push('/')
        props.flashFn.addFlashAc({
            type: 'alert-primary',
            text: '登录成功了',
            id: shortid.generate(),
            closeTime: 1000
        })
        // function Func(age) {
        //     this.age = age       
        // }
        // Func.prototype.name = 'garvin'
        // const func = new Func()
        // const res =  func.name
        // console.log("xxxxxxxxxxxxx",Func.prototype.constructor , func.__proto__.constructor);
    }
    return (
        <div>
            <form onSubmit={submit}>
                <div className="form-group">
                    <label htmlFor="username">username</label>
                    <input defaultValue={formData.username} onChange={changeInfo} name="username" type="username" className="form-control" />
                </div>
                <div className="form-group">
                    <label htmlFor="password">Password</label>
                    <input defaultValue={formData.password} onChange={changeInfo} name="password" type="password" className="form-control" />
                </div>

                <button type="submit" className="btn btn-primary">login</button>
            </form>
        </div>
    )
}
export default LoginForm
// module.exports LoginForm